package org.micropayment.provider.oauth.rest;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.context.annotation.Scope;
import org.springframework.security.Authentication;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.oauth.provider.ConsumerDetailsService;
import org.springframework.security.oauth.provider.token.OAuthProviderToken;
import org.springframework.security.oauth.provider.token.OAuthProviderTokenServices;
import org.springframework.security.userdetails.UserDetails;
import javax.ws.rs.core.Context;
import org.micropayment.model.MicropaymentAuthority;
import org.micropayment.model.MicropaymentUser;
import org.micropayment.model.service.MicropaymentUserDAO;
import org.micropayment.utils.DateUtils;
import org.springframework.security.oauth.provider.ConsumerDetails;
import org.springframework.security.oauth.provider.CoreOAuthProviderSupport;
import org.springframework.security.oauth.provider.OAuthProviderSupport;

/**
 *
 * @author jj
 */
@Path("/oauth/protected")
@Component
@Scope("request")
public class ProtectedResource {

    private static Logger logger =
        LoggerFactory.getLogger(ProtectedResource.class);

    @Autowired OAuthProviderTokenServices tokenServices;
    @Autowired ConsumerDetailsService consumerDetailsService;
    @Autowired MicropaymentUserDAO userDao;
    OAuthProviderSupport providerSupport;
    @Context HttpServletRequest request;

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    public String test() {
        String token = request.getParameter("oauth_token");
        logger.debug("############### token: " + token);
        String response = "Provider Rest test OK";
        OAuthProviderSupport providerSupport = new CoreOAuthProviderSupport();
        Map<String, String> parameters = providerSupport.parseParameters(request);
        token = parameters.get("oauth_token");
        MicropaymentUser user = getMicropaymentUser();
        userDao.save(user);
        logger.debug("############### user.getId(): " + user.getId());
        OAuthProviderToken providerToken = tokenServices.getToken(token);
        ConsumerDetails consumer =
                consumerDetailsService.loadConsumerByConsumerKey(providerToken.getConsumerKey());
        logger.debug("############### consumer name: " + consumer.getConsumerName());
        Authentication authentication =
                SecurityContextHolder.getContext().getAuthentication();
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails details = (UserDetails) authentication.getPrincipal();
            String username = details.getUsername();
            response.concat(" - " + username);
        }
        response.concat(" - transactionParameterAmount: " + 
                parameters.get("oauth_transaction_amount") + "\n");
        response.concat(" - transactionParameterDescription: " +
                parameters.get("oauth_transaction_description") + "\n");
        String transactionHeaderAmount = request.getHeader("oauth_transaction_amount");
        response.concat(" - transactionHeaderAmount: " + transactionHeaderAmount + "\n");
        String transactionHeaderDescription = request.getHeader("oauth_transaction_description");
        response.concat(" - transactionHeaderDescription: " + transactionHeaderDescription + "\n");
        SecurityContextHolder.getContext().setAuthentication(null);
        request.getSession().invalidate();
        return response;
    }

    public static MicropaymentUser getMicropaymentUser () {
        MicropaymentUser user = new MicropaymentUser ();
        user.setName("JJ");
        user.setPhone("55555");
        user.setPassword("nkk");
        user.setEmail("aaa@gmail.com");
        user.setAuthority(MicropaymentAuthority.ROLE_USER);
        user.setDateAdded(DateUtils.getTodayDate());
        user.setLastEntryDate(DateUtils.getTodayDate());
        user.setUserid("userID");
        user.setAccountExpired(Boolean.FALSE);
        user.setAccountLocked(Boolean.FALSE);
        user.setCredentialsExpired(Boolean.TRUE);
        user.setEnabled(Boolean.TRUE);
        return user;
    }


}
